package com.icss.train_sys_back.websocket;

import org.springframework.web.socket.*;
import org.springframework.web.socket.handler.TextWebSocketHandler;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;

@Component
public class WebSocketServer extends TextWebSocketHandler {

    private static final CopyOnWriteArraySet<WebSocketSession> sessions = new CopyOnWriteArraySet<>();

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        sessions.add(session);
        System.out.println("WebSocket连接建立: " + session.getId());
        session.sendMessage(new TextMessage("连接成功! Session ID: " + session.getId()));
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        String payload = message.getPayload();
        System.out.println("收到消息: " + payload + " from " + session.getId());

        // 添加安全验证
        if (isValidMessage(payload)) {
            broadcast("用户 " + session.getId() + " 说: " + payload);
        } else {
            session.sendMessage(new TextMessage("错误: 消息格式无效"));
        }
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        sessions.remove(session);
        System.out.println("WebSocket连接关闭: " + session.getId());
    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        System.out.println("WebSocket传输错误: " + exception.getMessage());
        session.close(CloseStatus.SERVER_ERROR);
    }

    // 消息验证方法 - 修复安全漏洞
    private boolean isValidMessage(String message) {
        if (message == null || message.trim().isEmpty()) {
            return false;
        }
        // 防止消息过长（DOS攻击防护）
        if (message.length() > 1000) {
            return false;
        }
        // 防止SQL注入和XSS攻击
        if (message.matches(".*[<>\"'].*")) {
            return false;
        }
        return true;
    }

    // 安全的广播方法
    public void broadcast(String message) {
        for (WebSocketSession session : sessions) {
            try {
                if (session.isOpen() && isValidMessage(message)) {
                    session.sendMessage(new TextMessage(message));
                }
            } catch (IOException e) {
                System.out.println("广播消息失败: " + e.getMessage());
            }
        }
    }

    public static int getConnectionCount() {
        return sessions.size();
    }
}
